<?php

/**
 * 首页
 * User: tsang
 * Date: 2017/9/14
 * Time: 20:11
 */

namespace app\admin\controller;
use think\Db;
use think\Exception;
use think\Request;

class Goods extends Common
{
	/*
	*	构造函数
	*/
	function __construct(){
		parent::__construct();
	}

	/*
	*	商品列表
	*/
    public function lists()
    {	
    	$where=array();
    	$keyword = input('keyword');
    	$goods_sn = input('goods_sn');

		if($keyword){
			$where['g.name']=array("like",'%'.$keyword.'%');
		}

		if($goods_sn){
			$where['g.goods_sn']=array("like",'%'.$goods_sn.'%');
		}
		
		if($this->admin_info['brand_id'] != 0){
			$where['g.brand_id'] = $this->admin_info['brand_id'];
		}

		$list = db("goods")->alias('g')
				->join('goods_category gc','gc.id=g.cid')
				->join('goods_brand b','b.id=g.brand_id')
				->where($where)->order("id desc")->field("g.id,g.name,g.image,gc.name as category_name,b.name as bname,g.status,g.goods_sn")->paginate(10);
		
		$config_uploads = IMG_PATH;
		$this->assign('config_uploads',$config_uploads);
    	$this->assign('keyword',$keyword);
    	$this->assign('goods_sn',$goods_sn);
    	$this->assign('list',$list);
        return $this->fetch();
    }

	
	/*
	*	商品添加
	 */
	public function add_goods()
	{	
		$this->goods_info();
		return $this->fetch();
	}

	/**
	 * 商品
	 */
	public function goods_info(){
		$id=input('id');

		if(request()->isPost()){
			$cid = input('cid/d');
			$name = input('name');
			$goods_sn = input('goods_sn');
			$images=input('photo/a');
			$status=input('status');
			$des=input('des');
			$content=input('content');
			$sort=input('sort');
			$key=input("key/a");
			$param=input("param/a");
			$postage=input("postage");

			$file=Request::instance()->file('goods_image');
			if($file){
				$info = $file->move(ROOT_IMG_PATH .'static/uploads');

				if($info){
					$data['image']= "/".str_replace('\\',"/",$info->getSaveName());
				}
			}

			$files = request()->file('photoname');

			if (!empty($files)) {
				foreach($files as $file){
					// 移动到框架应用根目录/public/uploads/ 目录下
					$info = $file->move(ROOT_IMG_PATH .'static/uploads');
					if($info){
						if($images) {
							array_push($images, $info->getSaveName());
						}else{
							$images[] = $info->getSaveName();
						}
					}
				}
			}

			if($images){
				$data['images']=serialize($images);
			}

			$file_top_image = request()->file('goods_top_image');

			if($file_top_image){
				$info = $file_top_image->move(ROOT_IMG_PATH .'static/uploads');

				if($info){
					$data['top_image']= "/".str_replace('\\',"/",$info->getSaveName());
				}
			}


			if(!empty($key)){
				$option=array();
				foreach($key as $k=>$v){
					$option[$k]['key']=$v;
					$option[$k]['value']=$param[$k];
				}

				$data['option']=serialize($option);
			}

			$data['cid'] = $cid;
			$data['name'] = $name;
			$data['des'] = $des;
			$data['content'] = htmlspecialchars($content);
			$data['goods_sn'] = $goods_sn;
			$data['sort'] = $sort;
			$data['postage'] = $postage;
			$data['brand_id'] = input('brand_id/d');

			if(empty($id)){

				$goods_id = db('goods')->insertGetId($data);
			}else{
				$data['status'] = $status;
				db('goods')->where(array('id'=>$id))->update($data);
				$goods_id = $id;
			}

			//商品规格更新
			$this->goods_specification($goods_id);

			$this->success("操作成功!",url('Goods/lists'));
		}

		if(!empty($id)){
			//查询商品
			$goods_result = db('goods')->where(array('id'=>$id))->find();
			$goods_result['images'] = unserialize($goods_result['images']);
			$goods_result['option'] = unserialize($goods_result['option']);
            $goods_result['content'] = htmlspecialchars_decode($goods_result['content']);
			//查询商品规格大分类
			$option_category_result = db('goods_option_category')->where(array('goodsid'=>$id))->order("id asc")->select();

			//查询小分类值
			$goods_option = db('goods_option')->where(array('goodsid'=>$id))->order("id asc")->select();
			$attrvalue=[];
			$attrname=[];
			foreach($goods_option as $key => $value){
				if($value['option_category'] == $option_category_result[0]['id']){
					$attrname[]=$value;
				}
                
				if(isset($option_category_result[1]['id'])){
					if($value['option_category'] == $option_category_result[1]['id']){
						$attrvalue[]=$value;
					}
				}
			}

			//查询options值
			$goods_option_value_result = db('goods_option_value')->where(array('goodsid'=>$id))->order("id asc")->select();
			$goods_option_value_count = count($goods_option_value_result);

			if(isset($option_category_result[1]['id'])){
				$attrvalue_count = count($attrvalue);
				$this->assign('attrvalue',$attrvalue);
				$this->assign('attrvalue_count',$attrvalue_count);
			}

			$goods_option_count = count($goods_option);

			$this->assign('goods_result',$goods_result);
			$this->assign('option_category_result',$option_category_result);
			$this->assign('goods_option_count',$goods_option_count);
			$this->assign('attrname',$attrname);
			$this->assign('goods_option_value_result',$goods_option_value_result);
			$this->assign('goods_option_value_count',$goods_option_value_count);
		}


		//查询商品分类
		$goods_category = db('goods_category')->select();
        if(empty($goods_category)) $this->error('请先去添加商品分类');

		//查询配置文件图片地址
		$config_uploads = IMG_PATH;

		$this->assign('id',$id);
		$this->assign('config_uploads',$config_uploads);
		$this->assign('goods_category',$goods_category);

		//查询该后台管理员管理的商品品牌
		$where_brand = [];
		if($this->admin_info['brand_id'] != 0){
			$where_brand['id'] = $this->admin_info['brand_id'];
		}
        $brand = db('goods_brand')->where($where_brand)->select();

        if(empty($brand)) $this->error('请先去添加商品品牌');
		$this->assign('brand',$brand);
	}

	/**
	 * 商品详情
	 */
	public function goods_detail(){
		$this->goods_info();
		return $this->fetch();
	}

	public function goods_specification($goods_id){
		//商品规格
		$attrtitleone = input('attrtitleone');
		$option_one = input('option_one/a');
		$attrtitletow = input('attrtitletow');
		$option_two = input('option_two/a');
		$attroldprice = input('attroldprice/a');
		$attrprice = input('attrprice/a');
		$attrtotal = input('attrtotal/a');
		
		//先清空表数据
		db('goods_option_category')->where(array('goodsid'=>$goods_id))->delete();
		db('goods_option')->where(array('goodsid'=>$goods_id))->delete();
		db('goods_option_value')->where(array('goodsid'=>$goods_id))->delete();

		$input = input();
		//var_dump($input);die;

		//大分类插入
		$attrtitleone_data[] = $attrtitleone;

		if(!empty($attrtitletow)){
			$attrtitleone_data[] = $attrtitletow;
		}

		foreach($attrtitleone_data as $key=>$value){
			//规格插入
			$goods_option_category_data['goodsid'] = $goods_id;
			$goods_option_category_data['title'] = $value;
			db('goods_option_category')->insert($goods_option_category_data);
			$goods_option_category_id[] = db('goods_option_category')->getLastInsID();
		}

		//小分类插入
		$option[] = $option_one;

		if(!empty($option_two)){
			$option[] = $option_two;
		}

		foreach ($option as $key => $value) {
			foreach($value as $k=>$v){
				$goods_option_data['goodsid'] = $goods_id;
				$goods_option_data['option_category'] = $goods_option_category_id[$key];
				$goods_option_data['title'] = $v;

				db('goods_option')->insert($goods_option_data);
			}
		}

		//拼接
		if(!empty($option_two)){
			foreach($option_one as $v){
				foreach($option_two as $d){
					$spec_name[]=$v.'&'.$d;
				}
			}
		}

		foreach($attrprice as $key => $value){
			$goods_option_value_data['goodsid'] = $goods_id;
			$goods_option_value_data['price'] = $attrprice[$key];
			$goods_option_value_data['oldprice'] = $attroldprice[$key];
			$goods_option_value_data['stock'] = $attrtotal[$key];

			$where['goodsid'] = $goods_id;
			if(!empty($option_two)){
				$specs_array = explode("&", $spec_name[$key]);
				$where['title'] = $specs_array[0];
				$goods_option_value_data['spec_name'] = $spec_name[$key];
			}else{
				$where['title'] = $option_one[$key];
				$goods_option_value_data['spec_name'] = $option_one[$key];
			}

			$goods_option_category_id = db('goods_option')->where($where)->field('id')->find();

			if(isset($specs_array[1])){
				$goods_option_id = db('goods_option')->where(array('goodsid'=>$goods_id,'title'=>$specs_array[1]))->field('id')->find();
				$goods_option_value_data['specs'] = $goods_option_category_id['id'].','.$goods_option_id['id'];
			}else{
				$goods_option_value_data['specs'] = $goods_option_category_id['id'];
			}

			db('goods_option_value')->insert($goods_option_value_data);
		}
	}

	/**
	 *   属性模板
	 */
	public function tpl(){

		return $this->fetch();
	}


	/*
		商品分类列表
	 */
	public function category_lists()
	{	
		$where = array();
		$keyword = input('keyword');
		if($keyword){
			$where['name']=array("like",'%'.$keyword.'%');
		}
		$data = db("goods_category")->where($where)->order("sort desc,p_id asc")->select();
        $list = array();
		if(!empty($data)){
		    $pids = array_column($data,'p_id');
            $data_count = array_count_values($pids);
            $list = array_slice($data,0,$data_count[0]);
            foreach ($list as &$l){
                if(array_key_exists($l['id'],$data_count)){
                    $l['children'] = array_slice($data,array_search($l['id'],$pids),$data_count[$l['id']]);
                }
            }
        }

		$this->assign('keyword',$keyword);
		$this->assign('img_path',IMG_PATH);
		$this->assign('list',$list);
		return $this->fetch();
	}


	/*
		添加商品分类
	 */
	public function add_category()
	{

		$id = input('id/d');
		$data = array();

		$model = db("goods_category");
		$parent = $model->where(['p_id' => 0])->select();
		$this->assign('parent',$parent);

		if(request()->isPost()){
			$data['name']=input("name");
			$data['sort']=input("sort");
            $data['p_id'] = input('p_id/d');

			$file=Request::instance()->file('goods_image');

			if($file){
				$info = $file->move(ROOT_IMG_PATH .'static/uploads');
				
				if($info){
					$data['image']= "/".str_replace('\\',"/",$info->getSaveName());
				}
			}

			if(!empty($id)){
				$data['status'] = input("status");
				$res=$model->where("id='$id'")->update($data);
			}else{
				$res=$model->insert($data);
			}
			if(!$res) $this->error("操作失败！");
			$this->success("操作成功！" ,url('Goods/category_lists'));
		}

		$goods_result = db("goods_category")->where("id='$id'")->find();
		$this->assign('img_path',IMG_PATH);
		$this->assign('goods_result',$goods_result);
		return $this->fetch();
	}

    /**
     * 删除商品分类
     * @parm
     * @return
     * @author tsang
     */
	public function del_category()
	{
		$id = input('id/d');
		$model = db("goods_category");
        $is = $model->where(['id' => $id])->find();
		if(!$is) $this->error('找不到该分类');

		$has_goods = db('goods')->where(['cid' => $id])->select();
		if($has_goods) $this->error('分类下存在商品，不能删除');

		$res=$model->where("id='$id'")->delete();

		if($res) $this->success("操作成功");
		$this->error("操作失败");
	}

    /**
     * 商品品牌
     * @author tsang
     */
    public function brand(){
	   $list = db("goods_brand")->select();
	   $this->assign('list',$list);
	   return $this->fetch();
    }

    /**
     * 商品品牌编辑/添加
     * @author tsang
     */
    public function brand_edit(){
        $id = input('id/d');
        $model = db('goods_brand');
        if($id > 0){
            $brand = $model->where(['id' => $id])->find();
            if(!$brand) $this->error('找不到该品牌');
            $this->assign('data',$brand);
        }
        if(request()->isPost()){
            $name = input('name/s');
            if($id > 0){
                if($model->where(['id' => $id])->update(['name' => $name])){
                    $this->success('更新成功',url('Goods/brand'));
                }else{
                    $this->error('更新失败',url('Goods/brand'));
                }
            }else{
                if($model->insert(['name' => $name])){
                    $this->success('添加成功',url('Goods/brand'));
                }else{
                    $this->error('添加失败',url('Goods/brand'));
                }
            }
        }
        return $this->fetch();
    }

    /**
     * 商品品牌删除
     * @author tsang
     */
    public function brand_del(){
        $id = input('id/d');
        $model = db('goods_brand');
        $brand = $model->where(['id' => $id])->find();
        if(!$brand) $this->error('找不到该品牌');
        $goods = db('goods')->where(['brand_id' => $id])->select();
        if(!empty($goods)) $this->error('品牌下存在商品，不能删除');
        if($model->where(['id' => $id])->delete()){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }



    public function test(){
        set_time_limit(0);
        $model = db('test');
        $time = time();
        for ($a = 0;$a<5;$a++){
            Db::startTrans();
            try{
                for ($i=0;$i<20000;$i++){
                    $data['t'] = time();
                    $data['a'] = 1234;
                    $data['b'] = 1;
                    $ins[] = $data;
                    //$model->insert($data);
                }

                $model->insertAll($ins);

                Db::commit();
            }catch (\Exception $e){
                echo $e->getMessage();
                //$this->error('132');
                Db::rollback();
            }
        }


        echo time() - $time;


    }
	
}